package com.zjp.shiro.concurrent;

import java.util.ArrayList;
import java.util.List;

import redis.clients.jedis.JedisCluster;

public class StorageTest2 {

	private int storage1  = 10; 
	private int storage2  = 10; 
	public static void main(String[] args) {
		StorageTest2 storageTest2 = new StorageTest2();
		List<Thread> threadList = new ArrayList<Thread>(200);
		for(int i = 0;i<100;i++){
			Thread buyThread = new Thread(new BuyThread2(storageTest2,"111"));
			threadList.add(buyThread);
		}
		for(int i = 0;i<100;i++){
			Thread buyThread = new Thread(new BuyThread2(storageTest2,"222"));
			threadList.add(buyThread);
		}
		for(Thread thread : threadList){
			thread.start();
		}
	}
	void buy(String productId){
		synchronized (productId) {
			if(productId.equals("111")){
				storage1--;
				if(storage1 < 0){
					System.out.println(Thread.currentThread().getName()+"没抢到"+productId);
				}else{
					System.err.println(Thread.currentThread().getName()+"抢到了"+productId);
				}
			}else{
				storage2--;
				if(storage2 < 0){
					System.out.println(Thread.currentThread().getName()+"没抢到"+productId);
				}else{
					System.err.println(Thread.currentThread().getName()+"抢到了"+productId);
				}
			}
		}
	}
}
class BuyThread2 implements Runnable{

	private StorageTest2 storageTest2;
	private String productId;
	public BuyThread2(StorageTest2 storageTest2,String productId){
		this.storageTest2 = storageTest2;
		this.productId = productId;
	}
	@Override
	public void run() {
		storageTest2.buy(productId);		
	}
}